from django.db import transaction
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from BYD_ERP.utils.get_inventory import get_inventory_by_goods
from purchase_info.models import PurchaseOrderModel, PurchaseOrderItemModel


class PurchaseOrderItemSerializer(serializers.ModelSerializer):
    """
        采购订单项目的序列化器
    """

    class Meta:
        model = PurchaseOrderItemModel
        fields = '__all__'


class PurchaseOrderSerializer(serializers.ModelSerializer):
    """
        新增和修改采购订单的序列化和反序列化
    """

    item_list = PurchaseOrderItemSerializer(many=True, write_only=True)
    # 采购订单列表中需要展示：商品信息，多个商品的名称+规格，中间使用逗号隔开
    goods_info = serializers.SerializerMethodField(read_only=True, label='包含采购订单中每个商品信息')

    class Meta:
        model = PurchaseOrderModel
        fields = '__all__'

    def get_goods_info(self, obj):
        """
            商品信息：商品1名称+商品1规格，商品2名称+商品2规格，…………
        """
        # 使用.all()返回的是列表
        if obj.item_list.all():
            result = []
            for item in obj.item_list.all():
                result.append(item.name + (item.specification if item.specification else ''))
            return ','.join(result)
        return ''

    def create(self, validated_data):
        item_list = validated_data.pop('item_list')
        with transaction.atomic():
            purchase_order = PurchaseOrderModel.objects.create(**validated_data)


            for item in item_list:
                pim = PurchaseOrderItemModel.objects.create(purchase_order=purchase_order, **item)
                goods = item.get('goods')
                pim.name = goods.name
                pim.specification = goods.specification
                pim.model_number = goods.model_number
                pim.save()
        return purchase_order

    def update(self, instance, validated_data):
        # instance：正在修改的采购订单
        if instance.status != '0':
            # 采购订单的状态/采购单的状态，0：未审核，1：已审核，2：部分入库，3：全部入库，4：已付定金，5：完成采购（货全部入库，付全款完成）
            raise ValidationError('采购订单已经生效，不能修改')
        item_list = validated_data.pop('item_list')
        # 如果之前有老数据（之前新增的采购订单项目数据）是需要删除掉的
        old_list = instance.item_list.all()
        with transaction.atomic():
            if old_list.exists():
                # 把老数据删除
                old_list.delete()
            for item in item_list:
                pim = PurchaseOrderItemModel.objects.create(purchase_order=instance, **item)
                goods = item.get('goods')
                pim.name = goods.name
                pim.specification = goods.specification
                pim.model_number = goods.model_number
                pim.save()
            result = super(PurchaseOrderSerializer, self).update(instance=instance, validated_data=validated_data)
        return result

class PurchaseOrderGetSerializer(serializers.ModelSerializer):
    """
        仅仅用于查询展示采购订单详情的序列化器
    """

    item_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = PurchaseOrderModel
        fields = '__all__'

    def get_item_list(self, obj):
        result = []  # 返回的是列表，列表中是多个字典
        if obj.item_list.all().exists():
            for item in obj.item_list.all():
                # item是一个PurchaseOrderItemModel的对象
                # 有一部分信息在PurchaseOrderItemModel里面没有
                # 只有在GoodsModel里面有：开票名称、开票型号、长度等
                item_dict = {}
                goods = item.goods
                warehouse = item.warehouse
                item_dict['goods'] = goods.id
                item_dict['name'] = goods.name  # 国标名称
                item_dict['specification'] = goods.specification  # 件号
                item_dict['model_number'] = goods.model_number  # 型号
                item_dict['length'] = goods.length
                item_dict['partner'] = goods.partner  # 合作方/厂家
                item_dict['brand'] = goods.brand  # 品牌
                item_dict['units'] = goods.units.basic_name
                item_dict['purchase_count'] = item.purchase_count
                item_dict['purchase_price'] = item.purchase_price
                item_dict['purchase_money'] = item.purchase_money
                item_dict['remark'] = item.remark
                # 该商品的总库存数量
                item_dict['cur_inventory_total'] = get_inventory_by_goods(goods.id)
                item_dict['cur_inventory_peitao'] = get_inventory_by_goods(goods.id, warehouse_id=1)

                result.append(item_dict)
        return result
